require_relative'GenRepository'

class CrossOperator
	attr_accessor :ratio

	def initialize(ratio)
		@ratio = ratio
	end
	
	def operate(breed_pool)
	new_pop=[]
		((breed_pool.size*@ratio).round).times{
			first_mate = breed_pool.sample
			second_mate = (breed_pool - [first_mate]).sample
			first_child = GenRepository.instance.get_chromosome
			second_child = GenRepository.instance.get_chromosome

		if first_mate.gens.first.gens_amount == 1 then
			simple_cross_over(first_mate,second_mate,first_child)
			simple_cross_over(second_mate,first_mate,second_child)
#super gens
		else
			i = 0
#make a zip by 4
			first_mate.gens.zip(second_mate.gens).each{|gen_par|
				simple_cross_over(gen_par.first,gen_par.last,first_child.gens.at(i))
				simple_cross_over(gen_par.last,gen_par.first,second_child.gens.at(i))
				i += 1
			}
		end
		new_pop << first_child
		new_pop << second_child
		}
	return new_pop
	end

	def simple_cross_over(c1,c2,child)
		max = c1.gens.size
		child.gens = []
		locus = Random.rand(max - 1) + 1
		c1.gens.take(locus).each{|gen| child.gens << gen}
		c2.gens.reverse.take(max-locus).reverse.each{|gen| child.gens << gen}
	end

end
